import PlayerTank from "./PlayerTank";
import { Dir } from "./Global";
import { log_debug } from "./Utils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class TouchControl extends cc.Component {
    @property(cc.Node)
    buttons: cc.Node[] = [];

    _player: PlayerTank = null;
    _node: cc.Node = null;

    onLoad() {
        this._node = cc.find("/Canvas");
        this._player = cc.find("/Canvas/GameLayer/MapLayer/player").children[0].getComponent(PlayerTank);
 
        if (cc.sys.isMobile) {
            this.node.active = true;
        } else {
            this.node.active = false;
        }
 
        if (CC_DEBUG) {
            this.node.active = true;
        }
    }

    onEnable() {
        this._node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this, true);
        this._node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this, true);
    }
 
    onDisable() {
        this._node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this, true);
        this._node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this, true);
    }

    onTouchStart(event: cc.Event.EventTouch) {
        // 触摸点世界坐标
        let touchPos = event.touch.getLocation();
        // 转换成画布内的节点坐标
        let nodePos = this._node.convertToNodeSpaceAR(touchPos);
        // touch节点包围盒
        let touchNodeBox = this.node.getBoundingBox();
        if (touchNodeBox.contains(nodePos)) {
            // 将触摸点坐标转到touch节点下
            let pos = this.node.convertToNodeSpaceAR(touchPos);
            if (this.buttons[0].getBoundingBox().contains(pos)) {
                this._player.move(Dir.LEFT);
            } else if (this.buttons[1].getBoundingBox().contains(pos)) {
                this._player.move(Dir.UP);
            } else if (this.buttons[2].getBoundingBox().contains(pos)) {
                this._player.move(Dir.RIGHT);
            } else if (this.buttons[3].getBoundingBox().contains(pos)) {
                this._player.move(Dir.DOWN);
            }
        } else {
            this._player.shoot();
        }
    }

    onTouchEnd(event: cc.Event.EventTouch) {
        let touchPos = event.touch.getLocation();
        let nodePos = this._node.convertToNodeSpaceAR(touchPos);
        let touchNodeBox = this.node.getBoundingBox();
        if (touchNodeBox.contains(nodePos)) {
            let pos = this.node.convertToNodeSpaceAR(touchPos);
            if (this.buttons[0].getBoundingBox().contains(pos) ||
            this.buttons[1].getBoundingBox().contains(pos) ||
            this.buttons[2].getBoundingBox().contains(pos) ||
            this.buttons[3].getBoundingBox().contains(pos)) {
                this._player.moveStop();
            }
        }
    }
}
